package io.finer.erp.jeecg.bas.controller;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import io.finer.erp.jeecg.bas.dto.BasCustomerAddressDTO;
import io.finer.erp.jeecg.bas.dto.BasCustomerDTO;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasCustomerCateLabel;
import io.finer.erp.jeecg.bas.entity.BasCustomerRegional;
import io.finer.erp.jeecg.bas.entity.BasSalesman;
import io.finer.erp.jeecg.bas.entity.Region;
import io.finer.erp.jeecg.bas.entity.ZrkUserCustomer;
import io.finer.erp.jeecg.bas.mapper.RegionMapper;
import io.finer.erp.jeecg.bas.service.IBasCustomerCateLabelService;
import io.finer.erp.jeecg.bas.service.IBasCustomerRegionalService;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.IBasSalesmanService;
import io.finer.erp.jeecg.bas.service.IZrkUserCustomerService;
import io.finer.erp.jeecg.bas.vo.BasCustomerRegoinVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 客户
 * @Author: jeecg-boot
 * @Date:   2020-04-01
 * @Version: V1.0
 */
@Api(tags="客户")
@RestController
@RequestMapping("/bas/basCustomer")
@Slf4j
public class BasCustomerController extends JeecgController<BasCustomer, IBasCustomerService> {
	@Autowired
	private IBasCustomerService basCustomerService;
	@Autowired
	private IBasCustomerRegionalService customerRegionalService;
	@Autowired
	private RegionMapper regionMapper;
	@Autowired
	private IBasCustomerCateLabelService customerLabelService;
	
	/**
	 * 分页列表查询
	 *
	 * @param basCustomer
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "客户-分页列表查询")
	@ApiOperation(value="客户-分页列表查询", notes="客户-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BasCustomer basCustomer,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Integer area = null;
		String a = basCustomer.getArea();
		if(oConvertUtils.isNotEmpty(basCustomer.getArea())) {
			area = Integer.valueOf(basCustomer.getArea());
			basCustomer.setArea(null);
		}
		QueryWrapper<BasCustomer> queryWrapper = QueryGenerator.initQueryWrapper(basCustomer, req.getParameterMap());
		if(oConvertUtils.isNotEmpty(a)) {
			List<Integer> idList = Lists.newArrayList();
			List<Region> list = regionMapper.getAllChildRegionHasChild(a);
			if(list!=null && list.size()>0) {
				for(Region region:list) {
					idList.add(region.getId());
				}
			}
			idList.add(area);
			queryWrapper.in("area", idList);
		}
		Page<BasCustomer> page = new Page<BasCustomer>(pageNo, pageSize);
		IPage<BasCustomer> pageList = basCustomerService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param basCustomer
	 * @return
	 */
	@AutoLog(value = "客户-添加")
	@ApiOperation(value="客户-添加", notes="客户-添加")
	@PostMapping(value = "/add")
	@CacheEvict(value=CacheConstant.BAS_CUSTOMER_ADDRESS, allEntries=true)
	public Result<?> add(@RequestBody BasCustomer basCustomer) {
		if(oConvertUtils.isEmpty(basCustomer.getRegionId())) {
			basCustomerService.save(basCustomer);
		}else {
			basCustomerService.save(basCustomer);
			BasCustomerRegional cr = new BasCustomerRegional();
			cr.setCustomerId(basCustomer.getId());
			cr.setRegionId(basCustomer.getRegionId());
			customerRegionalService.save(cr);
		}
//		basCustomer.setIsAllocated(0);
//		basCustomerService.save(basCustomer);
//		String area = basCustomer.getArea().substring(0, 2);
//		
//		Collection<BasSalesman> coll = bsService.list();
//		if(null!=coll&&coll.size()>0) {
//			Iterator<BasSalesman> itera = coll.iterator();
//			while(itera.hasNext()) {
//				BasSalesman bs = itera.next();
//				if(bs.getUserArea().indexOf(area)>=0) {
//					ZrkUserCustomer zuc = new ZrkUserCustomer();
//					zuc.setCreateBy(basCustomer.getCreateBy());
//					zuc.setCreateTime(basCustomer.getCreateTime());
//					zuc.setUserId(bs.getUserId());
//					zuc.setCustomerId(basCustomer.getId());
//					zuc.setDisType(2);
//					zucService.save(zuc);
//					basCustomer.setIsAllocated(1);
//					basCustomerService.updateById(basCustomer);
//				}
//			}
//		}
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param basCustomer
	 * @return
	 */
	@AutoLog(value = "客户-编辑")
	@ApiOperation(value="客户-编辑", notes="客户-编辑")
	@PutMapping(value = "/edit")
	@CacheEvict(value=CacheConstant.BAS_CUSTOMER_ADDRESS, allEntries=true)
	public Result<?> edit(@RequestBody BasCustomer basCustomer) {
		basCustomerService.updateById(basCustomer);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "客户-通过id删除")
	@ApiOperation(value="客户-通过id删除", notes="客户-通过id删除")
	@DeleteMapping(value = "/delete")
	@CacheEvict(value=CacheConstant.BAS_CUSTOMER_ADDRESS, allEntries=true)
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		basCustomerService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "客户-批量删除")
	@ApiOperation(value="客户-批量删除", notes="客户-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@CacheEvict(value=CacheConstant.BAS_CUSTOMER_ADDRESS, allEntries=true)
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.basCustomerService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "客户-通过id查询")
	@ApiOperation(value="客户-通过id查询", notes="客户-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BasCustomer basCustomer = basCustomerService.getById(id);
		if(basCustomer==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(basCustomer);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param basCustomer
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasCustomer basCustomer) {
        return super.exportXls(request, basCustomer, BasCustomer.class, "客户");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BasCustomer.class);
    }
    
    /**
     * @Description 获取所有客户
     * @return
     * Create at: 2020-12-15 16:45:13
     * @author: duany
     * Revision:
     *    2020-12-15 16:45:13 - first revision by duany
     *        
     */
    @PostMapping("getCustomers")
    public Result<?> getCustomers(){
    	return this.basCustomerService.getCustomers();
    }
    
    /**
	 * 根据地域Id查询客户信息
	 * @param page
	 * @param
	 * @return
	 */
    @GetMapping(value = "/customerRegionList")
    public Result<?> customerRegionList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			   HttpServletRequest req) {
    	String regionId = req.getParameter("regionId");
    	String name = req.getParameter("name");
		Page<BasCustomerDTO> page = new Page<BasCustomerDTO>(pageNo, pageSize);
//		IPage<BasCustomer> pageList = basCustomerService.page(page, queryWrapper);
		IPage<BasCustomerDTO> pageList = basCustomerService.getCustomerByRegionId(page, regionId,name);
		return Result.ok(pageList);
	}
    
    /**
     * 给指定地域添加客户
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @PostMapping(value = "/addCustomerRegion")
    public Result<String> addCustomerRegion(@RequestBody BasCustomerRegoinVO basCustomerRegoinVO) {
        Result<String> result = new Result<String>();
        try {
            String regionId = basCustomerRegoinVO.getRegionId();
            for(String basCustomerId:basCustomerRegoinVO.getCustomerIdList()) {
                BasCustomerRegional sysUserRole = new BasCustomerRegional();
                sysUserRole.setCustomerId(basCustomerId);
                sysUserRole.setRegionId(regionId);
                QueryWrapper<BasCustomerRegional> queryWrapper = new QueryWrapper<BasCustomerRegional>();
                queryWrapper.eq("customer_id", basCustomerId).eq("region_id",regionId);
                BasCustomerRegional one = customerRegionalService.getOne(queryWrapper);
                if(one==null){
                	customerRegionalService.save(sysUserRole);
                }

            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }
    
    /**
     *   删除指定地域的客户关系
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @DeleteMapping(value = "/deleteCustomerRegion")
    public Result<BasCustomerRegional> deleteCustomerRegion(@RequestParam(name="regionId") String regionId,
                                                    @RequestParam(name="customerId",required=true) String customerId
    ) {
        Result<BasCustomerRegional> result = new Result<BasCustomerRegional>();
        try {
            QueryWrapper<BasCustomerRegional> queryWrapper = new QueryWrapper<BasCustomerRegional>();
            queryWrapper.eq("region_id", regionId).eq("customer_id",customerId);
            customerRegionalService.remove(queryWrapper);
            result.success("删除成功!");
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }
    
    /**
     * 批量删除指定地域的客户关系
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteCustomerRegionBatch", method = RequestMethod.DELETE)
    public Result<BasCustomerRegional> deleteUserRoleBatch(
            @RequestParam(name="regionId") String regionId,
            @RequestParam(name="customerIds",required=true) String customerIds) {
        Result<BasCustomerRegional> result = new Result<BasCustomerRegional>();
        try {
            QueryWrapper<BasCustomerRegional> queryWrapper = new QueryWrapper<BasCustomerRegional>();
            queryWrapper.eq("region_id", regionId).in("customer_id",Arrays.asList(customerIds.split(",")));
            customerRegionalService.remove(queryWrapper);
            result.success("删除成功!");
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }
    
    /**
     * @Description 
     * @param customerId
     * @return
     * Create at: 2021-08-11 10:24:43
     * @author: duany
     * Revision:
     *    2021-08-11 10:24:43 - first revision by duany
     *        
     */
    @GetMapping("/getCustomerLabel")
    public Result<BasCustomerCateLabel> getCustomerCateLabel(String customerId){
    	BasCustomerCateLabel label = customerLabelService.lambdaQuery()
    					.eq(BasCustomerCateLabel::getCustomerId, customerId)
    					.orderByDesc(BasCustomerCateLabel::getCreateTime)
    					.last(" limit 1 ").one();
    	Result<BasCustomerCateLabel> result = new Result<>();
    	result.setResult(label);
    	result.setSuccess(Boolean.TRUE);
    	result.setCode(CommonConstant.SC_OK_200);
    	return result;
    }
}
